package dom;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class XMLParseUpd {
    Document doc=null;
    public void getDocument(){
        // 获取解析器工厂
        DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();

        // 获取解析器
        try {
            DocumentBuilder bd=dbf.newDocumentBuilder();
            doc= bd.parse("src/main/resources/phone.xml");
        } catch (ParserConfigurationException e) {
            e.printStackTrace();;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }
    }

    public void showInfo(){
        // 获取<Brand>的所有节点集合
        NodeList nodeList=doc.getElementsByTagName("Brand");
        for (int i = 0; i < nodeList.getLength(); i++) {
            Element brandElement=(Element) nodeList.item(i);
            String brandName=brandElement.getAttribute("name");
            if(brandName.equals("三星")){
                brandElement.setAttribute("name","SAMSUNG");
            }
        }
        try {
            // 保存xml文件
            TransformerFactory transformerFactory=TransformerFactory.newInstance();
            Transformer transformer=transformerFactory.newTransformer();
            DOMSource domSource=new DOMSource(doc);
            // 设置编码类型
            transformer.setOutputProperty(OutputKeys.ENCODING,"gb2312");
            StreamResult result=new StreamResult(new FileOutputStream("src/main/resources/phone.xml"));
            transformer.transform(domSource,result);
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        XMLParseUpd parse=new XMLParseUpd();
        parse.getDocument();
        parse.showInfo();
    }
}
